var app = getApp()
let canRoll = true, //加控制，防止用户点击两次
  num = 1, //用在动画上，让用户在第二次点击的时候可以接着上次转动的角度继续转
  lotteryArrLen = 0, //放奖品的数组的长度
  lottery = [],

  lottery_ = new Array(10);
Page({
  data: {
    showBulb: 1,       //设置灯泡定时变颜色
    interval: '',
    win: false,
    noWin: false,
    hiddenShow: true,
    coupon: {},
    point: '',
    ifCoupon: false,
    ifPoint: false
    // lottery: [{ name: '优惠券' }, { name: '积分' }, { name: '优惠券' }]
  },

  onLoad() {
    //console.log("奖池大小：" + lottery.length)
    lottery = [{ name: '优惠券', src: '/images/liwu0.png' }, { name: '积分', src: '/images/liwu1.png' }, { name: '优惠券', src: '/images/liwu2.png' }]
    this.getAwards()
    this.setPlateData()
    
  },
  setPlateData() { //设置奖品数组
    lotteryArrLen = lottery.length; //获取奖品数组的长度，用来判断
    if (lotteryArrLen < 2) { //数组的奖品只有一个，扩展数组的长度到4
      let evenArr = new Array(4); //创建一个数组，方便操作。
      for (let i = 0; i < 4; i++) {
        if (i % 2 == 1) { //这里为什么要取1是为了在默认的界面将指针放在谢谢的地方，防止别人拿着中奖的截图来要奖品
          evenArr[i] = lottery[0]; //将原数组的内容赋值到新的数组
        } else {
          let obj = {id: 0, name: '谢谢'}
          evenArr[i] = obj
        }
      }
      lottery = [...evenArr]; //将整合好的数组赋值给lottery数组
    } else { //数组中的奖品超过1个，则正常扩展数组，扩展的数组为原来的2倍
      let dataLen = 0; //用来放原来数组的索引
      let length = lotteryArrLen * 2
      let evenArr = new Array(length); //创建扩展数组
      for (let i = 0; i < (lotteryArrLen * 2); i++) {
        if (i % 2 == 1) {
          evenArr[i] = lottery[dataLen]; //将原来数组的值赋值给新数组
          dataLen++; //原来数组的索引加一
        } else {
          let obj = {id: 0, name: '谢谢'}
          evenArr[i] = obj
        }
      }
      lottery = [...evenArr]; //将整合好的数组赋值给lottery数组
    }

    lotteryArrLen = lottery.length; //获取新的数组长度
    
    
    this.setData({
      lottery: lottery //设置好值，用于页面展示
    })
  },
  startRollTap() { //开始转盘
    let that = this;
    //this.roll()
    if (canRoll) {
      this.roll()
    }
  },

  onUnload: function () {
    let that = this
    clearInterval(that.data.interval)
  },

  /**
   * 获取奖品
   */
  getAwards: function () {
    let token = wx.getStorageSync('token')
    let that = this
    wx.request({
      url: app.apiUrl('/market/prize/getprizelist'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {

      },
      success: function (res) {
        console.log('getAwards')
        console.log(res.data)

        if (res.data.code > app.globalData.successCode) {
          wx.showToast({
            title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 0)
        } else {
          lottery = res.data.data
          for (var i = 0; i < lottery.length; i++) {
            lottery[i].name = lottery[i].type == 1 ? '优惠券' : '积分'
          }
          that.setPlateData(); //执行设置转盘表面的文字
          let aniData = wx.createAnimation({ //创建动画对象
            duration: 2000,
            timingFunction: 'ease'
          });
          that.aniData = aniData; //将动画对象赋值给this的aniData属性
          that.data.interval = setInterval(function () {
            that.setData({
              showBulb: that.data.showBulb + 1
            })
            //console.log('bulb:' + that.data.showBulb)
          }, 1000)
        }

      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        // wx.hideToast()
        //console.log(res)
      }
    })
  },

  /**
   * 开始
   */
  roll: function () {
    let token = wx.getStorageSync('token')
    let that = this
    //that.aniData.rotate(1).step()
    wx.request({
      url: app.apiUrl('/market/prize/playbigwhell'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {

      },
      success: function (res) {
        console.log('playbigwheel')
        console.log(res.data)
        if (res.data.code > app.globalData.successCode) {
          console.log('error')
          wx.showToast({
            title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 0)
        } else {
  
          canRoll = false;
          let aniData = that.aniData; //获取this对象上的动画对象
          //let rightNum = ~~(Math.random() * lotteryArrLen); //生成随机数
          let rightNum = that.getRightIndex(res.data.data.prize_id)
          aniData.rotate(3600 * num - 360 / lotteryArrLen * rightNum).step(); //设置转动的圈数

          setTimeout(function () {
            canRoll = true
            if (res.data.data.code == 0) {
              that.setData({
                noWin: true,
                hiddenShow: false,
                win: false
              })
            } else if (res.data.data.code == 1) {
              that.setData({
                point: res.data.data.prize,
                noWin: false,
                hiddenShow: false,
                win: true,
                ifPoint: true,
                ifCoupon: false
              })

            } else {
              that.setData({
                coupon: res.data.data.prize,
                noWin: false,
                hiddenShow: false,
                win: true,
                ifPoint: false,
                ifCoupon: true
              })
            }
          }.bind(that), 2000)

          that.setData({
            aniData: aniData.export()
          })
          num++;
          
        }
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        // wx.hideToast()
        //console.log(res)
      }
    })
  },

  /**
   * 根据id获取当前奖品的索引
   */
  getRightIndex: function (id) {
    for (var i = 0; i < lottery.length; i++) {
      if (lottery[i].id == id)
        return i
    }
    return 0
  },
  toMyAwards: function (e) {
    wx.navigateTo({
      url: "/pages/my-award-list/index"
    })
  },
  closePopup: function () {
    this.setData({
      hiddenShow: true
    })
  },
  toMyCoupons: function () {
    wx.navigateTo({
      url: "/pages/my-coupon-list/index"
    })
  }
})
